<template>
  <div class="register-page">
    <div class="register-container">
      <div class="register-header">
        <h1 class="register-title">注册</h1>
        <p class="register-subtitle">加入校园活动报名系统</p>
      </div>
      
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        label-position="top"
      >
        <!-- 用户类型选择 -->
        <el-form-item label="用户类型" prop="role">
          <el-radio-group v-model="registerForm.role" size="large">
            <el-radio-button label="STUDENT">学生</el-radio-button>
            <el-radio-button label="ORGANIZER">组织者</el-radio-button>
          </el-radio-group>
        </el-form-item>
        
        <!-- 基本信息 -->
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            size="large"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>
        
        <!-- 学生信息 -->
        <template v-if="registerForm.role === 'STUDENT'">
          <el-form-item label="学号" prop="studentNumber">
            <el-input
              v-model="registerForm.studentNumber"
              placeholder="请输入学号"
              size="large"
              prefix-icon="Postcard"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="registerForm.name"
              placeholder="请输入真实姓名"
              size="large"
              prefix-icon="User"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="专业" prop="major">
            <el-input
              v-model="registerForm.major"
              placeholder="请输入专业"
              size="large"
              prefix-icon="School"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="年级" prop="grade">
            <el-select
              v-model="registerForm.grade"
              placeholder="请选择年级"
              size="large"
              style="width: 100%"
            >
              <el-option label="大一" value="1" />
              <el-option label="大二" value="2" />
              <el-option label="大三" value="3" />
              <el-option label="大四" value="4" />
              <el-option label="研一" value="5" />
              <el-option label="研二" value="6" />
              <el-option label="研三" value="7" />
            </el-select>
          </el-form-item>
        </template>
        
        <!-- 组织者信息 -->
        <template v-if="registerForm.role === 'ORGANIZER'">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="registerForm.name"
              placeholder="请输入真实姓名"
              size="large"
              prefix-icon="User"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="联系方式" prop="contact">
            <el-input
              v-model="registerForm.contact"
              placeholder="请输入手机号或邮箱"
              size="large"
              prefix-icon="Phone"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="组织/部门" prop="organization">
            <el-input
              v-model="registerForm.organization"
              placeholder="请输入所属组织或部门"
              size="large"
              prefix-icon="OfficeBuilding"
              clearable
            />
          </el-form-item>
        </template>
        
        <!-- 协议同意 -->
        <el-form-item prop="agreement">
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意
            <el-link type="primary" @click="showAgreement = true">用户协议</el-link>
            和
            <el-link type="primary" @click="showPrivacy = true">隐私政策</el-link>
          </el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="register-button"
            :loading="loading"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
        
        <el-form-item>
          <div class="login-link">
            已有账号？
            <el-link type="primary" @click="$router.push('/login')">
              立即登录
            </el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 用户协议对话框 -->
    <el-dialog v-model="showAgreement" title="用户协议" width="600px">
      <div class="agreement-content">
        <h3>校园活动报名系统用户协议</h3>
        <p>欢迎使用校园活动报名系统。在使用本系统前，请仔细阅读以下条款：</p>
        <ol>
          <li>用户应提供真实、准确的个人信息进行注册。</li>
          <li>用户有义务保护自己的账号安全，不得将账号借给他人使用。</li>
          <li>用户在使用系统时应遵守相关法律法规和校园规定。</li>
          <li>系统管理方有权对违规用户进行处理。</li>
          <li>本协议的最终解释权归系统管理方所有。</li>
        </ol>
      </div>
      <template #footer>
        <el-button @click="showAgreement = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 隐私政策对话框 -->
    <el-dialog v-model="showPrivacy" title="隐私政策" width="600px">
      <div class="privacy-content">
        <h3>隐私政策</h3>
        <p>我们重视您的隐私保护，特制定本隐私政策：</p>
        <ol>
          <li>我们收集的信息仅用于系统功能实现和服务提供。</li>
          <li>我们不会向第三方泄露您的个人信息。</li>
          <li>您有权查看、修改或删除自己的个人信息。</li>
          <li>我们采用安全措施保护您的信息安全。</li>
          <li>如有隐私相关问题，请联系系统管理员。</li>
        </ol>
      </div>
      <template #footer>
        <el-button @click="showPrivacy = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { validateEmail, validatePhone } from '@/utils'

const router = useRouter()
const userStore = useUserStore()

const registerFormRef = ref()
const loading = ref(false)
const showAgreement = ref(false)
const showPrivacy = ref(false)

const registerForm = reactive({
  role: 'STUDENT',
  username: '',
  password: '',
  confirmPassword: '',
  agreement: false,
  // 学生信息
  studentNumber: '',
  name: '',
  major: '',
  grade: '',
  // 组织者信息
  contact: '',
  organization: ''
})

// 自定义验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const validateContact = (rule, value, callback) => {
  if (registerForm.role === 'ORGANIZER' && value) {
    if (!validateEmail(value) && !validatePhone(value)) {
      callback(new Error('请输入有效的邮箱地址或手机号'))
    }
  }
  callback()
}

const registerRules = {
  role: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  studentNumber: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d{8,12}$/, message: '学号应为8-12位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { validator: validateContact, trigger: 'blur' }
  ],
  organization: [
    { required: true, message: '请输入组织/部门', trigger: 'blur' }
  ],
  agreement: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意用户协议和隐私政策'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 监听角色变化，清空相关字段
watch(() => registerForm.role, (newRole) => {
  if (newRole === 'STUDENT') {
    registerForm.contact = ''
    registerForm.organization = ''
  } else {
    registerForm.studentNumber = ''
    registerForm.major = ''
    registerForm.grade = ''
  }
})

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    const userData = {
      username: registerForm.username,
      password: registerForm.password,
      role: registerForm.role
    }
    
    // 根据角色添加额外信息
    if (registerForm.role === 'STUDENT') {
      userData.student = {
        studentNumber: registerForm.studentNumber,
        name: registerForm.name,
        major: registerForm.major,
        grade: parseInt(registerForm.grade)
      }
    } else if (registerForm.role === 'ORGANIZER') {
      userData.organizer = {
        name: registerForm.name,
        contact: registerForm.contact,
        organization: registerForm.organization
      }
    }
    
    await userStore.register(userData)
    
    ElMessage.success('注册成功，请登录')
    router.push('/login')
    
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.register-container {
  background: white;
  border-radius: 12px;
  padding: 40px;
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-title {
  font-size: 2rem;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.register-subtitle {
  color: #606266;
  font-size: 14px;
}

.register-form {
  margin-bottom: 20px;
}

.register-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
}

.login-link {
  text-align: center;
  color: #606266;
  font-size: 14px;
}

.agreement-content,
.privacy-content {
  line-height: 1.6;
}

.agreement-content h3,
.privacy-content h3 {
  margin-bottom: 16px;
  color: #303133;
}

.agreement-content ol,
.privacy-content ol {
  padding-left: 20px;
}

.agreement-content li,
.privacy-content li {
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-container {
    padding: 30px 20px;
    margin: 10px;
    max-width: none;
  }
  
  .register-title {
    font-size: 1.5rem;
  }
}
</style>